#!/bin/bash
##工作路径
work_path=$(dirname $(readlink -f $0))
smarfile=""
source ${work_path}/fun.devicehealth.sh

function getTestResult(){
	logfile=$1
	iotype=$2

#cat /tmp/fio-sdc-write.log  |grep ' write:'  | awk '{print $2$3}' | sed 's/,/;/g'
	cat $logfile |grep " ${iotype}:" | awk '{print $2$3}' | sed 's/,/;/g'
}


function getStrValue(){
	grepKey=$1
	grepFile=$2
	grep "${grepKey}" $grepFile |head -n 1| awk -F":" '{print $2}' | awk '{gsub(/^\s+|\s+$/, "");print}'

}

function runFio(){
	device=$1
	rw=$2
	bs=$3
	size=$4
	name=fio-${device}-${rw}
	logfile="/tmp/$name.log"
	errlog="/tmp/$name.err"

	fio --filename=/dev/$device -iodepth=64 -ioengine=libaio -direct=1 -rw=$rw -bs=$bs -size=$size -numjobs=8 -runtime=60 --group_reporting -name=$name > $logfile 2>$errlog
	if [ $? -ne 0 ];then
		cat $errlog
		exit 1
	fi

	iops_write=`getTestResult $logfile "write" |sed "s/IOPS/${rw}-IOPS/g" | sed "s/BW/${rw}-BW/g"`

	iops_read=`getTestResult $logfile "read" | sed "s/IOPS/${rw}-IOPS/g" | sed "s/BW/${rw}-BW/g"`

	echo "$iops_write$iops_read"
}

#1. disk name
#2. test mode (randwrite,randread,write,read)
#
function startDiskTest(){
	diskName=$1
	sn=$2
	resultcode="0"
	resultmsg=""


	sn=`getStrValue 'Serial Number' $smarfile`

	size=`lsblk -o NAME,SIZE |grep -w $diskName |awk '{print $2}'`
	pn=`lsblk -o NAME,MODEL |grep -w $diskName |awk '{print $2 $3}'`

	# echo -n "name=$diskName;sn=${sn};size=${size};pn=${pn};"

	printStu="resultcode=0;resultmsg="

	if [ "$detectionType" -eq 1 ];then

		write_result=`runFio "$diskName" "write" "512K" 1G`
		if [ $? -ne 0 ];then
			printStu="resultcode=1;resultmsg=${write_result}"
		fi

		read_result=`runFio "$diskName" "read" "512K" 1G`
		if [ $? -ne 0 ];then
			printStu="resultcode=1;resultmsg=${read_result}"
		fi

		randwrite_result=`runFio "$diskName" "randwrite" "4k" 1G`
		if [ $? -ne 0 ];then
			printStu="resultcode=1;resultmsg=${randwrite_result}"
		fi

		randread_result=`runFio "$diskName" "randread" "4k" 1G`
		if [ $? -ne 0 ];then
			printStu="resultcode=1;resultmsg=${randread_result}"
		fi
	fi

	## device health
	# smarfile="/tmp/${diskName}.smart.log"
	# smartctl -a /dev/${diskName} > $smarfile
	health=`getDeviceHealth $smarfile`

	##测试正常
	echo "name=$diskName;sn=${sn};size=${size};pn=${pn};${write_result};${read_result};${randwrite_result};${randread_result};health=${health};${printStu};category=DISK"
}

function main(){
	for disk in `lsblk -d |egrep -v 'NAME|loop|sr'  |awk '{print $1}'`
	do
		smarfile="/tmp/${disk}.smart.log"
		smartctl -a /dev/${disk} > $smarfile

		cat $smarfile |grep 'USB bridge' > /dev/null
		if [  $? -eq 0 ];then
			continue
		fi

		## start test
		startDiskTest $disk &
	done
	wait
}
cycle=$1
detectionType=${2:-'1'}
main 


